package com.shujia.wyh.day14.tcpdemo1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
    使用多线程的方式改进服务器端的代码，使服务器端代码可以监听多个客户端的连接
 */
public class ServerDemo2 {
    public static void main(String[] args) throws Exception {
        //创建服务器的Socket对象
        ServerSocket ss = new ServerSocket(12345);

        //写一个死循环，一直监听客户端的连接
        while (true) {
            Socket socket = ss.accept();
            //将监听到的客户端封装成线程对象
            new ServerClient(socket).start();
        }
    }
}


class ServerClient extends Thread {
    private Socket socket;

    public ServerClient(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InetAddress inetAddress = socket.getInetAddress();
        //获取用户的ip的地址
        String ip = inetAddress.getHostAddress();
        //获取用户名
        String hostName = inetAddress.getHostName();
        System.out.println("===========================================================");
        System.out.println("ip为：" + ip + "的用户：" + hostName + "已连接，正在通信中......");
        System.out.println("===========================================================");
        long start = System.currentTimeMillis();

        try {
            try {
                //获取通道中的输入流对象，用于接收客户端发来的消息
                InputStream inputStream = socket.getInputStream();
                //获取通道中的输出流对象，用于给客户端反馈数据
                OutputStream outputStream = socket.getOutputStream();

                while (true) {
                    //获取当前时间戳
                    long timestmp = System.currentTimeMillis();
                    Date date = new Date(timestmp);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf.format(date);

                    byte[] bytes = new byte[1024];
                    int length = inputStream.read(bytes);
                    String info = new String(bytes, 0, length);
                    System.out.println(time);
                    System.out.println("用户：" + hostName + "发来一条消息：" + info);


                    //给客户端一个反馈
                    outputStream.write("服务器已经收到消息了！！".getBytes());
                    outputStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            long end = System.currentTimeMillis();
            System.out.println("ip为：" + ip + "的用户：" + hostName + "共在线"+(end-start)/1000+"秒，客户端已经下线.......");
        }


    }
}